<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores/index'
import { useRoute } from 'vue-router'
import { onMounted, ref, provide } from 'vue'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import type { ConsultOrderItem } from '@/types/room'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import type { Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
const store = useUserStore()
const route = useRoute()
const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

// 给后代组件提供数据 和修改数据的方法
provide('consult', consult)
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
})

// io 有参数
// 参数1: 服务器域名 不传,默认是当前域名
// 参数2: 配置参数
// 建立连接
const socket = io(baseURL, {
  auth: {
    token: `Bearer ${store.user?.token}`
  },
  query: {
    orderId: route.query.orderId
  }
})
onMounted(() => {
  //
  // 监听连接成功
  socket.on('connect', () => {
    // 建立连接成功
    console.log('连接成功了')
    list.value = []
  })

  socket.on('error', () => {
    console.log('连接失败')
  })

  socket.on('disconnect', () => {
    console.log('已经断开连接了')
  })

  // 获取聊天记录
  const initMsg = ref(true)
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log(data)
    const arr: Message[] = []
    // 转换常规消息列表
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    // --------
    list.value.unshift(...arr)
    loading.value = false
    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    nextTick(() => {
      if (initMsg.value) {
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        initMsg.value = false
      }
    })
  })
  // 订单状态改变服务端会通知
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
  // 监听接受消息
  socket.on('receiveChatMsg', async (e) => {
    list.value.push(e)
    await nextTick()
    socket.emit('updateMsgStatus', e.id)
    window.scrollTo(0, document.body.scrollHeight)
  })
})

// 发消息 第一个参数相等于自定义事件名(前端和后端约定好的)   后端会监听这个事件, 你触发这个事件的时候后端能知道,并进行一些业务逻辑
// socket.emit('chat message', '消息内容')

// 接收消息
// socket.on('chat message', (e) => {
// e 就是服务端发送回来的消息
// })

// 断开连接
// socket.close()

// 发送消息
const sendText = (text: string) => {
  // 发送消息
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo.id,
    //key值 msgType是小写 后面值是大写
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
// 发送图片
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo.id,
    //key值 msgType是小写 后面值是大写
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}
// 聊天记录
const loading = ref(false)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page" v-if="consult">
    <!-- navbar -->
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <!-- 状态栏 -->
    <RoomStatus
      :status="consult.status"
      :countdown="consult.countdown"
    ></RoomStatus>
    <!-- 消息区域 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage :list="list"></RoomMessage>
    </van-pull-refresh>

    <!-- 操作区 -->
    <RoomAction
      :disabled="consult.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></RoomAction>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
